import { HttpClient } from '@capacitor-community/http';
import { loadingController, toastController } from '@ionic/core/components';
import { Preferences } from '@capacitor/preferences';

const API_URL = '/api';

export class ApiService {
  private static async showLoading(message: string = 'Please wait...') {
    const loading = await loadingController.create({
      message,
      duration: 10000,
    });
    await loading.present();
    return loading;
  }

  private static async hideLoading(loading: HTMLIonLoadingElement) {
    if (loading) {
      await loading.dismiss();
    }
  }

  private static async showToast(message: string, color: string = 'danger') {
    const toast = await toastController.create({
      message,
      duration: 3000,
      color,
    });
    await toast.present();
  }

  private static async getHeaders() {
    const { value: token } = await Preferences.get({ key: 'auth_token' });
    return {
      'Content-Type': 'application/json',
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
    };
  }

  private static async handleError(error: any) {
    console.error('API Error:', error);

    if (error.status === 401) {
      await Preferences.remove({ key: 'auth_token' });
    }

    const message = error.message || 'An error occurred. Please try again.';
    await this.showToast(message);
    throw error;
  }

  static async post<T>(endpoint: string, data: any, showLoader = true): Promise<T> {
    let loading;
    try {
      if (showLoader) {
        loading = await this.showLoading();
      }

      const headers = await this.getHeaders();
      const response = await HttpClient.post({
        url: `${API_URL}${endpoint}`,
        headers,
        data,
      });

      if (response.status >= 400) {
        throw new Error(response.data.message || 'Request failed');
      }

      return response.data;
    } catch (error) {
      await this.handleError(error);
      throw error;
    } finally {
      if (loading) {
        await this.hideLoading(loading);
      }
    }
  }

  static async get<T>(endpoint: string, showLoader = true): Promise<T> {
    let loading;
    try {
      if (showLoader) {
        loading = await this.showLoading();
      }

      const headers = await this.getHeaders();
      const response = await HttpClient.get({
        url: `${API_URL}${endpoint}`,
        headers,
      });

      if (response.status >= 400) {
        throw new Error(response.data.message || 'Request failed');
      }

      return response.data;
    } catch (error) {
      await this.handleError(error);
      throw error;
    } finally {
      if (loading) {
        await this.hideLoading(loading);
      }
    }
  }
}